<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-区域开台记录`"
		width="900px"
		:confirm-btn-loading="saveBtnLoading"
		fullscreen
		:permission-prefix="permissionPrefix"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<div ref="box1">
			<el-alert v-if="hasError" type="error" show-icon description="服务端异常!" size="large" class="margin-bottom-10"></el-alert>
			<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="90px" :show-message="false">
				<el-row class="flex-start-center-wrap">
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.workshopName }}</span>
							<jk-select v-else v-model="ruleForm.workshopId" :option-list="workshopList" size="medium" class="width-100-percent" placeholder="区域" @change="onWorkshopChange"></jk-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="日期" prop="belongDate">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.belongDate }}</span>
							<jk-date-picker v-else v-model="ruleForm.belongDate" type="date" size="medium" placeholder="日期" @change="onDateChange" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="班次" prop="scheduleShiftId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.shiftName }}</span>
							<el-select v-else v-model="ruleForm.scheduleShiftId" :disabled="!!ruleForm.id || !ruleForm.belongDate" clearable placeholder="班次" size="medium" class="width-100-percent" @change="onScheduleShiftChange">
								<el-option
									v-for="item in scheduleShiftList"
									:key="item.id"
									:label="`${item.shiftName} (${item.beginTime} ~ ${item.endTime})`"
									:value="item.id"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="班组" prop="scheduleGroupId">
							<span v-if="ruleForm.id" class="read-only-2">{{ ruleForm.groupName }}</span>
							<jk-select v-else v-model="ruleForm.scheduleGroupId" :disabled="!ruleForm.scheduleShiftId" :option-list="scheduleGroupList" size="medium" label-key-name="groupName" class="width-100-percent" placeholder="班组" @change="onGroupChange"></jk-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item class="margin-bottom-10" label="统计员" prop="empId">
							<remote-search-emp-input
								size="medium"
								placeholder="统计员"
								only-key="empId"
								query-name="empName"
								:form-data="ruleForm"
								@on-select="onSelectEmpChange"
							></remote-search-emp-input>
						</el-form-item>
					</el-col>
					<el-col :span="18">
						<el-form-item class="margin-bottom-10" label="备注">
							<el-input v-model="ruleForm.remark" type="textarea" :rows="1"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</div>
		<div :style="{ height: `${dialogTableHeight + 90}px` }" style="overflow-y: auto;overflow-x: hidden;">
			<div
				v-for="(areaItem, areaIndex) in ruleForm.areaList"
				:key="areaIndex"
				class="margin-bottom-10"
			>
				<el-button type="primary" plain class="width-100-percent margin-bottom-4" size="large">
					<div style="font-size: 18px;font-weight: 700;">
						<span class="el-icon-c-scale-to-original"></span>
						<span>{{ areaItem.workshopAreaName }}</span>
					</div>
				</el-button>
				<el-row :gutter="10">
					<el-col :span="15">
						<jk-table ref="productTable" :loading="showLoading" :size="tableSize" :footer-method="footerMethod" :show-footer="true" border :data="areaItem.productList">
							<vxe-column title="操作" align="center" field="operation" :width="62">
								<template slot-scope="scope">
									<el-button icon="el-icon-delete" size="mini" @click="onDeleteRowBtn(scope, areaIndex)"></el-button>
								</template>
							</vxe-column>
							<vxe-column title="规格" align="left" field="productModels" :min-width="110" />
							<vxe-column title="批号" align="left" field="batchCode" :min-width="100"></vxe-column>
							<vxe-column title="上机数" align="right" field="upQty" :width="70" />
							<vxe-column title="关台数" align="right" field="closeQty" :width="90">
								<template slot-scope="scope">
									<jk-number-input v-model="scope.row.closeQty" size="small" :max="scope.row.upQty" @change="onPrdChange($event, areaIndex, scope, 1)"></jk-number-input>
								</template>
							</vxe-column>
							<vxe-column title="实际开台" align="right" field="openQty" :width="100">
								<template slot-scope="scope">
									<jk-number-input v-model="scope.row.openQty" size="small" :max="scope.row.upQty" @change="onPrdChange($event, areaIndex, scope, 2)"></jk-number-input>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>
					<el-col :span="9">
						<jk-table ref="postTable" :loading="showLoading" :size="tableSize" :footer-method="footerMethod" :show-footer="true" border :data="areaItem.postList">
							<vxe-column title="岗位" align="left" field="postName" :min-width="90" />
							<vxe-column title="到岗数" align="right" field="totalQty" :min-width="80">
								<template slot-scope="scope">
									<jk-number-input v-model="scope.row.totalQty" size="small"></jk-number-input>
								</template>
							</vxe-column>
							<vxe-column title="请假数" align="right" field="leaveQty" :min-width="80">
								<template slot-scope="scope">
									<jk-number-input v-model="scope.row.leaveQty" size="small"></jk-number-input>
								</template>
							</vxe-column>
						</jk-table>
					</el-col>
				</el-row>
			</div>
			<el-tag class="margin-bottom-4" size="large">通用岗位</el-tag>
			<el-row>
				<el-col :span="12">
					<jk-table ref="commonTable" :size="tableSize" :loading="showLoading" :footer-method="footerMethod" :show-footer="true" border :data="ruleForm.generalPostList">
						<vxe-column title="岗位" align="left" field="postName" :min-width="90" />
						<vxe-column title="到岗数" align="right" field="totalQty" :min-width="80">
							<template slot-scope="scope">
								<jk-number-input v-model="scope.row.totalQty" size="mini"></jk-number-input>
							</template>
						</vxe-column>
						<vxe-column title="请假数" align="right" field="leaveQty" :min-width="80">
							<template slot-scope="scope">
								<jk-number-input v-model="scope.row.leaveQty" size="mini"></jk-number-input>
							</template>
						</vxe-column>
					</jk-table>
				</el-col>
			</el-row>
		</div>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        spinReportWorkshopProductOpenRecordCreate,
        spinReportWorkshopProductOpenRecordUpdate,
        spinReportWorkshopProductOpenRecordGet,
        spinReportWorkshopProductOpenRecordData
    } from '../../../api/production/workshopOpenRecord';
    import checkboxMachineDialog from '../../schedule/empMachine/components/checkbox-machine-dialog';
    import remoteSearchEmpInput from '../../production/order/components/remote-search-emp-input';
    import remoteSearchProductInput from '../../production/order/components/remote-search-product-input';
    import remoteSearchBatchCodeInput
        from '../../production/qhPrd/productConfigCotton/components/remote-search-batch-code-input';
    import { formatDate, tipsBar } from '../../../utils/jk/jk-tool';
    import { workforcemanagementScheduleList } from '../../../api/schedule/scheduling';
    import { spinWorkshopAreaPage } from '../../../api/basicData/workshopArea';
    import XEUtils from 'xe-utils';
    import { systemPostPage } from '../../../api/system/post';
    export default {
        components: {
            remoteSearchBatchCodeInput,
            remoteSearchProductInput,
            checkboxMachineDialog,
            remoteSearchEmpInput
        },
        props: {
            // 页面权限的前缀
            permissionPrefix: {
                type: String,
                default: ''
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            defaultTypeCode: {
                type: String,
                default: ''
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                hasError: false,
                tableSize: 'large',
                allPost: [],
                postList: [],
                activeTab: '0',
                scheduleGroupList: [],
                workshopList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                workshopAreaList: [],
                ruleForm: {
                    id: null,
                    workshopAreaId: null,
                    workshopAreaName: null,
                    scheduleGroupId: null,
                    belongDate: '',
                    scheduleShiftId: null,
                    scheduleId: null,
                    empId: null,
                    empName: '',
                    remark: '',
                    workshopId: null,
                    generalPostList: [],
                    matchProductList: [],
                    areaList: []
                },
                rules: {
                    belongDate: [{ required: true, trigger: 'change' }],
                    scheduleGroupId: [{ required: true, trigger: 'change' }],
                    empId: [{ required: true, trigger: 'change' }],
                    workshopAreaId: [{ required: true, trigger: 'change' }],
                    scheduleShiftId: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }]
                },
                scheduleShiftList: []
            };
        },
        methods: {
            onPrdChange(e, areaIndex, scope, type) {
                if (type === 1) {
                    const val = (this.ruleForm.areaList[areaIndex].productList[scope.rowIndex].upQty || 0) - (this.ruleForm.areaList[areaIndex].productList[scope.rowIndex].closeQty || 0);
                    this.$set(this.ruleForm.areaList[areaIndex].productList[scope.rowIndex], 'openQty', val);
                } else if (type === 2) {
                    const val = (this.ruleForm.areaList[areaIndex].productList[scope.rowIndex].upQty || 0) - (this.ruleForm.areaList[areaIndex].productList[scope.rowIndex].openQty || 0);
                    this.$set(this.ruleForm.areaList[areaIndex].productList[scope.rowIndex], 'closeQty', val);
                }
            },
            onDeleteRowBtn(scope, areaIndex) {
                this.$delete(this.ruleForm.areaList[areaIndex], scope.rowIndex, 1);
            },
            footerMethod({ columns, data }) {
                const keys = ['upQty', 'closeQty', 'openQty', 'totalQty', 'zhiGuan', 'leaveQty'];
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return '合计';
                        }
                        if (keys.includes(column.field)) {
                            return XEUtils.sum(data, column.field);
                        }
                        return null;
                    })
                ];
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['machineName']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onWorkshopAreaChange() {
                this.getStatisticData();
            },
            onGroupChange(e) {
                this.$set(this.ruleForm, 'areaList', []);
                if (e) {
                    const scheduleGroupItem = this.scheduleGroupList.find(x => x.id === e);
                    this.$set(this.ruleForm, 'scheduleGroupId', scheduleGroupItem.id);
                    this.$set(this.ruleForm, 'groupId', scheduleGroupItem.groupId);
                    this.$set(this.ruleForm, 'groupCode', scheduleGroupItem.groupCode);
                    this.$set(this.ruleForm, 'groupName', scheduleGroupItem.groupName);
                }
                this.getStatisticData();
            },
            getStatisticData() {
                if (!this.ruleForm.scheduleShiftId || !this.ruleForm.scheduleGroupId) return false;
                this.showLoading = true;
                const shiftItem = this.scheduleShiftList.find(x => x.id === this.ruleForm.scheduleShiftId) || {};
                const groupItem = this.scheduleGroupList.find(x => x.id === this.ruleForm.scheduleGroupId) || {};
                spinReportWorkshopProductOpenRecordData({
                    workshopId: this.ruleForm.workshopId,
                    belongDate: this.ruleForm.belongDate,
                    shiftId: shiftItem.shiftId,
                    groupId: groupItem.groupId
                }).then(res => {
                    this.showLoading = false;
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                        resData.areaList = resData.areaList ? resData.areaList.map(x => {
                            x.productList = x.productList || [];
                            x.matchProductList = x.matchProductList || [];
                            x.empList = x.empList || [];
                            return x;
                        }) : [];
                        this.$set(this.ruleForm, 'areaList', resData.areaList ? resData.areaList : []);
                    }
                });
            },
            onWorkshopChange() {
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'workshopAreaId', null);
                this.$set(this.ruleForm, 'scheduleId', null);
                this.$set(this.ruleForm, 'scheduleShiftId', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.$set(this.ruleForm, 'groupId', null);
                this.$set(this.ruleForm, 'groupCode', null);
                this.$set(this.ruleForm, 'groupName', null);
                this.scheduleShiftList = [];
                this.$set(this.ruleForm, 'areaList', []);
                this.getDateScheduleShiftOptionRequest();
            },
            onScheduleShiftChange(e) {
                let item = {};
                if (e) {
                    item = this.scheduleShiftList.find(x => x.id === e);
                } else {
                    item = {
                        id: null,
                        shiftId: null,
                        shiftName: null,
                        scheduleId: null
                    };
                }
                this.$set(this.ruleForm, 'groupId', null);
                this.$set(this.ruleForm, 'groupCode', null);
                this.$set(this.ruleForm, 'groupName', null);
                this.scheduleGroupList = item.scheduleGroupList;
                this.$set(this.ruleForm, 'areaList', []);
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'scheduleId', item.scheduleId);
                this.$set(this.ruleForm, 'shiftId', item.id);
                this.$set(this.ruleForm, 'shiftCode', item.shiftCode);
                this.$set(this.ruleForm, 'shiftName', item.shiftName);
            },
            onDateChange() {
                this.$set(this.ruleForm, 'scheduleGroupId', null);
                this.$set(this.ruleForm, 'shiftId', null);
                this.$set(this.ruleForm, 'shiftName', null);
                this.$set(this.ruleForm, 'shiftCode', null);
                this.$set(this.ruleForm, 'groupId', null);
                this.$set(this.ruleForm, 'groupCode', null);
                this.$set(this.ruleForm, 'groupName', null);
                this.scheduleShiftList = [];
                this.$set(this.ruleForm, 'areaList', []);
                this.getDateScheduleShiftOptionRequest();
            },
            getDateScheduleShiftOptionRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.belongDate) {
                    return workforcemanagementScheduleList({
                        belongDate: [this.ruleForm.belongDate, this.ruleForm.belongDate],
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res;
                            if (resData && resData.length) {
                                this.scheduleShiftList = resData[0].scheduleShiftList;
                            } else {
                                tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                            }
                        }
                    });
                }
            },
            onSelectBatchChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'batchCode', e.batchCode);
                }
            },
            onSelectProductChange(e, rowIndex, cellIndex) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productId', e.id);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productCode', e.code);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productName', e.name);
                    this.$set(this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList[cellIndex], 'productModels', e.models);
                }
            },
            onSelectEmpChange(e) {
                if (Object.keys(e).length) {
                    this.$set(this.ruleForm, 'empId', e.id);
                    this.$set(this.ruleForm, 'empName', e.name);
                }
            },
            onAddMachineBtn({ rowIndex }) {
                this.ruleForm.subTitleList[rowIndex].productUseCommunicationItemList.push({
                    'batchCode': '',
                    'batchId': 0,
                    'color': '',
                    'dosage': '',
                    'extendText': '',
                    'productCode': '',
                    'productId': 0,
                    'productModels': '',
                    'productName': '',
                    'remark': '',
                    'subTitle': ''
                });
            },
            onAddBtn() {
                this.ruleForm.subTitleList.push({
                    subTitle: null,
                    productUseCommunicationItemList: []
                });
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                const item = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = item.code;
                params.workshopName = item.name;

                const areaItem = this.workshopAreaList.find(x => x.id === params.workshopAreaId) || {};
                params.workshopAreaCode = areaItem.code;
                params.workshopAreaName = areaItem.name;
                return params;
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                this.hasError = false;
                // 新增
                if (!this.dataId) {
                    this.ruleForm.id = null;
                    spinReportWorkshopProductOpenRecordCreate(this.getParamData()).then(res => {
                        this.saveBtnLoading = false;
                        if (res.data.status === 200) {
                            this.$tipsBar(this, 'save');
                            this.$emit('on-finish', res.data.res);
                        } else {
                            this.hasError = true;
                        }
                    });
                    return;
                }

                // 编辑
                spinReportWorkshopProductOpenRecordUpdate(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    } else {
                        this.hasError = true;
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinReportWorkshopProductOpenRecordGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getWorkshopAreaListRequest() {
                return spinWorkshopAreaPage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.workshopAreaList = res.data.res;
                    }
                });
            },
            getPostListRequest() {
                return systemPostPage({
                    auditState: 1
                }).then(res => {
                    if (res.data.status === 200) {
                        this.allPost = res.data.res ? res.data.res.map(x => {
                            return {
                                totalQty: 0,
                                leaveQty: 0,
                                processCode: x.processCode,
                                sortNum: x.sortNum,
                                postId: x.id,
                                postName: x.name
                            };
                        }) : [];
                        this.postList = this.allPost.filter(x => ['XS', 'LT'].includes(x.processCode)).sort((a, b) => {
                            return a.sortNum - b.sortNum;
                        });
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'belongDate', formatDate(Date.now()));
                    this.$set(this.ruleForm, 'empId', this.$store.state.user.empInfo.id);
                    this.$set(this.ruleForm, 'empName', this.$store.state.user.empInfo.name);
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                await this.getPostListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getWorkshopAreaListRequest();
                await this.getDateScheduleShiftOptionRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            },
            ruleForm: {
                handler() {
                    this.$nextTick(() => {
                        const arr1 = this.$refs.productTable;
                        const arr2 = this.$refs.postTable;
                        if (arr1) {
                            arr1.forEach(x => {
                                x.$refs.xTable.updateFooter();
                            });
                        }
                        if (arr2) {
                            arr2.forEach(x => {
                                x.$refs.xTable.updateFooter();
                            });
                        }
                        this.$refs.commonTable.$refs.xTable.updateFooter();
                    });
                },
                deep: true
            }
        }
    };
</script>
<style scoped lang="scss">
    .option-item-title {
        height: 38px;
        font-size: 14px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #e8eaec;
        border-radius: 4px 4px 0 0;
    }
</style>
